package com.coolingme.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

/**
 * ES配置类
 * ElasticsearchRestTemplate 基于 RestHighLevelClient 客户端的。
 * 需要自定义配置类，继承AbstractElasticsearchConfiguration，
 * 并实现 elasticsearchClient()抽象方法，创建 RestHighLevelClient 对象
 *
 * @author wangyue
 * @date 2021/7/30 9:57
 */
//@ConfigurationProperties(prefix = "elasticsearch")
@Slf4j
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {

    /**
     * ES 访问host
     */
    @Value("${elasticsearch.host}")
    private String ES_HOST;

    /**
     * ES 访问port
     */
    @Value("${elasticsearch.port}")
    private Integer ES_PORT;

    /**
     * ES 访问用户
     */
    @Value("${elasticsearch.userName}")
    private String userName;

    /**
     * ES 访问密码
     */
    @Value("${elasticsearch.password}")
    private String password;

    @Bean(name = "restHighLevelClient")
    @Override
    public RestHighLevelClient elasticsearchClient() {
        log.info("ES连接初始化 地址：{},端口：{}，用户名：{}，密码：{}", ES_HOST, ES_PORT, userName, password);
        RestClientBuilder builder = RestClient.builder(new HttpHost(ES_HOST, ES_PORT));
        if (StrUtil.isNotBlank(userName) && StrUtil.isNotBlank(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            builder.setHttpClientConfigCallback(f -> f.setDefaultCredentialsProvider(credentialsProvider));
        }
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }

}
